package com.findviewbydream.evil.eda.Answer;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.findviewbydream.evil.eda.Bean.AnswerBean;
import com.findviewbydream.evil.eda.Bean.AnswerOverItemBean;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.AnswerEvent;
import com.findviewbydream.evil.eda.EventBus.AnswerResultEvent;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Dialog.CustomMaterialDialog;
import com.findviewbydream.evil.eda.Utils.Dialog.LoadingDialog;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Answer
 * 时间：16-8-24 上午9:15
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：答题主界面
 ********************************************/
public class AnswerActivity extends AppCompatActivity
{
    private int itemId;
    private int position;
    private Toolbar toolbar;
    private TextView submit;
    private TextView toolbarTitle;
    private FrameLayout container_left;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle barDrawerToggle;

    private ArrayList<AnswerBean> list;
    public static ArrayList<AnswerFragment> answerFragmentList;
    public static boolean[] anwerBool;

    private boolean flag = false;/*用于弹出窗口，防止点击窗口消失*/
    private Bundle bundle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.answer_activity);

        initView();

        getIntentData();/*获得Intent数据*/
        setDrawerlayout();/*设置侧滑栏*/

        onClick();
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        container_left = (FrameLayout) findViewById(R.id.container_left);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        submit = (TextView) findViewById(R.id.submit);
        toolbarTitle = (TextView) findViewById(R.id.toolbarTitle);
    }

    /**
     * 获得Intent数据，
     * 获取itemid
     */
    private void getIntentData()
    {
        itemId = getIntent().getIntExtra("itemId", 0);
        position = getIntent().getIntExtra("position", 0);
        //Utils.Logger(itemId);
        toNetWork();
    }

    /*EventBus -> 注册*/
    @Override
    protected void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    /*EventBus -> 操作  更改toolbar标题*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AnswerEvent event)
    {
        toolbarTitle.setText(event.message);
    }

    /*EventBus -> 销毁*/
    @Override
    protected void onStop()
    {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 网络连接，获取题目内容
     */
    private void toNetWork()
    {
        LoadingDialog.showDialog(this);
        OkHttpUtils.post()
                .url(Data.IP + "AnswerServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .addParams("itemId", itemId + "")
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        LoadingDialog.dismissDialog();
                        Snackbar.make(findViewById(R.id.drawerLayout),
                                "加载失败，请重试！", Snackbar.LENGTH_LONG)
                                .setAction("重试", new View.OnClickListener()
                                {
                                    @Override
                                    public void onClick(View view)
                                    {
                                        toNetWork();
                                    }
                                }).show();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        LoadingDialog.dismissDialog();

                        if (response.equals("MOREOVERTIMES"))
                        {
                            final CustomMaterialDialog dialog = new CustomMaterialDialog(AnswerActivity.this);
                            dialog.setMessage("    您今天的回答数目已经达到上限!\n"
                                    + "    为了软件更好的发展，防止一些有“意图”的用户刷题，"
                                    + "特此，我们加入了题目限制。\n"
                                    + "    请您明天再来答题赚取流量，对此带来的不便特请您谅解，"
                                    + "感谢您的对Eda易答的支持！")
                                    .setButtonText("好滴")
                                    .setCanBack(false)
                                    .setButtonOnClick((OnBtnClickL) () -> {
                                        dialog.dismiss();
                                        new Handler().postDelayed(() -> finish(), 300);
                                    }).show();
                        }
                        else
                        {
                            list = new Gson().fromJson(response
                                    , new TypeToken<List<AnswerBean>>()
                                    {
                                    }.getType());

                            if (list.size() == 0)
                            {
                                final CustomMaterialDialog dialog = new CustomMaterialDialog(AnswerActivity.this);
                                dialog.setMessage("啊哦，题目被偷走了，先看看别的吧！")
                                        .setButtonText("好滴")
                                        .setCanBack(false)
                                        .setButtonOnClick(new OnBtnClickL()
                                        {
                                            @Override
                                            public void onBtnClick()
                                            {
                                                dialog.dismiss();
                                                new Handler().postDelayed(new Runnable()
                                                {
                                                    @Override
                                                    public void run()
                                                    {
                                                        finish();
                                                    }
                                                }, 300);
                                            }
                                        }).show();
                            }
                            else
                            {
                                initLeftMenu();/*初始化左侧菜单*/
                            }
                        }
                    }
                });
    }

    /**
     * 设置侧滑栏
     */
    private void setDrawerlayout()
    {
        barDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
        {
        };
        barDrawerToggle.syncState();
        drawerLayout.addDrawerListener(barDrawerToggle);
    }

    /**
     * 初始化左侧菜单
     */
    private void initLeftMenu()
    {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentById(R.id.container_left) == null)
            fragmentTransaction.add(R.id.container_left, AnswerLeftMenu.newInstance(list));

        fragmentTransaction.commit();

        initFragmentData();/*初始化主界面Fragment*/
    }

    /**
     * 初始化主界面Fragment 数据，todo：初始化放在左侧菜单中
     */
    private void initFragmentData()
    {
        answerFragmentList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++)
        {
            answerFragmentList.add(AnswerFragment.newInstance(list.get(i), i));
        }

        Utils.Log(list.size());
        Utils.Log(answerFragmentList.size());

        anwerBool = new boolean[answerFragmentList.size()];
    }


    /**
     * 点击事件
     */
    private void onClick()
    {
        submit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                bundle = new Bundle();
                if (anwerBool != null)
                {
                    for (Boolean b : anwerBool)
                    {
                        Utils.Log(b);
                    }
                    int sum = 0;
                    int yes = 0;
                    int no = 0;
                    for (int i = 0; i < anwerBool.length; i++)
                    {
                        AnswerBean bean = list.get(i);

                        if (anwerBool[i])
                        {
                            sum += bean.getFlow();
                            yes++;
                        }
                    }
                    no = anwerBool.length - yes;

                    bundle.putInt("sum", sum);
                    bundle.putInt("yes", yes);
                    bundle.putInt("no", no);

                    submitToNetWork();
                }
            }
        });
    }


    /**
     * 提交答案的网络连接
     */
    private void submitToNetWork()
    {
        /*弹出窗口*/
        @SuppressLint("InflateParams") View view = LayoutInflater
                .from(this).inflate(R.layout.answer_result_dialog, null);

        final SpinKitView loading = (SpinKitView) view.findViewById(R.id.loading);


        final LinearLayout error = (LinearLayout) view.findViewById(R.id.error);
        TextView retry = (TextView) view.findViewById(R.id.retry);
        final TextView errorTextView = (TextView) view.findViewById(R.id.errorTextView);

        final LinearLayout over = (LinearLayout) view.findViewById(R.id.over);
        final TextView overTextView = (TextView) view.findViewById(R.id.overTextView);

        final LinearLayout success = (LinearLayout) view.findViewById(R.id.success);
        final TextView successTextView = (TextView) view.findViewById(R.id.successTextView);


        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        builder.setCancelable(false);
        builder.setTitle("提交结果");
        builder.setPositiveButton("确认", (dialogInterface, i) -> {
            if (flag)
                finish();
        });
        builder.show();

        retry.setOnClickListener(view1 -> submitToNetWork());

        OkHttpUtils.post()
                .url(Data.IP + "AnswerOverItemServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .addParams("itemId", itemId + "")
                .addParams("yes", bundle.getInt("yes") + "")
                .addParams("no", bundle.getInt("no") + "")
                .addParams("sumFlow", bundle.getInt("sum") + "")
                .addParams("type", "SUBMIT")
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(final Call call, Exception e, int id)
                    {
                        flag = true;
                        loading.setVisibility(View.GONE);
                        error.setVisibility(View.VISIBLE);
                        errorTextView.setText("提交失败，请点击重试！");
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(String response, int id)
                    {
                        loading.setVisibility(View.GONE);

                        if (response.equals("MOREOVERTIMES"))
                        {
                            final CustomMaterialDialog dialog = new CustomMaterialDialog(AnswerActivity.this);
                            dialog.setMessage("    您今天的回答数目已经达到上限!\n"
                                    + "    为了软件更好的发展，防止一些有“意图”的用户刷题，"
                                    + "特此，我们加入了题目限制。\n"
                                    + "    请您明天再来答题赚取流量，对此带来的不便特请您谅解，"
                                    + "感谢您的对Eda易答的支持！")
                                    .setButtonText("好滴")
                                    .setCanBack(false)
                                    .setButtonOnClick((OnBtnClickL) () -> {
                                        dialog.dismiss();
                                        new Handler().postDelayed(() -> finish(), 300);
                                    }).show();
                        }
                        /*成功*/
                        else if (response.equals("SUCCESS"))
                        {
                            flag = true;
                            submit.setClickable(false);
                            EventBus.getDefault().post(new AnswerResultEvent(position));
                            success.setVisibility(View.VISIBLE);
                            if (bundle.getInt("sum") == 0)
                                successTextView.setText("啊哦，您好像都没有答对…………下次努力吧！！！");
                            else
                                successTextView.setText("恭喜您获得" + bundle.getInt("sum") + "M流量，\n流量将于次日/月打入您的手机中，\n具体详见使用指南。");
                        }
                        /*失败*/
                        else if (response.equals("FAIL"))
                        {
                            error.setVisibility(View.VISIBLE);
                            errorTextView.setText("提交失败，请点击重试！");
                        }
                        /*内部错误*/
                        else if (response.equals("ERROR"))
                        {
                            error.setVisibility(View.VISIBLE);
                            errorTextView.setText("内部错误，请点击重试！");
                        }
                        /*已经提交过*/
                        else if (response.startsWith("ISOVER"))
                        {
                            flag = true;
                            EventBus.getDefault().post(new AnswerResultEvent(position));

                            over.setVisibility(View.VISIBLE);
                            response = response.replace("ISOVER", "");/*由于加了前缀辨别json，需要去掉前缀*/
                            AnswerOverItemBean itemBean = new Gson().fromJson(response
                                    , new TypeToken<AnswerOverItemBean>()
                                    {
                                    }.getType());

                            overTextView.setText("抱歉，您已经提交过该题目，\n请勿重复提交！\n\n");
                            overTextView.append("题目ID：" + itemBean.getItemId() + "\n");
                            overTextView.append("获得流量：" + itemBean.getSumFlow() + "\n");
                            overTextView.append("完成时间：" + itemBean.getOvertime() + "\n");
                        }
                        /*未知错误*/
                        else
                        {
                            error.setVisibility(View.VISIBLE);
                            errorTextView.setText("未知错误：\n" + response);
                        }
                    }
                });
    }


}
